import "./index.less";
import { Suspense, useEffect, useMemo, useState } from "react";
import { Canvas } from "@react-three/fiber";
import {
  Sky,
  OrbitControls,
  KeyboardControls,
  PointerLockControls,
  CameraShake,
  Preload,
  AdaptiveDpr,
} from "@react-three/drei";
import { Physics } from "@react-three/rapier";
import { Perf } from "r3f-perf";

import { reducer, useConnect } from "../utils/dva17";
import { NMold, RSetState } from "../config/constants";

import { Test, isTest } from "./test";
import Player from "./player";
import Pov from "./pov";
import OtherPlayers from "./otherPlayers";
import Building from "./building";
import Audios from "./audios";
import Ocean from "./ocean";
import Clouds from "./clouds";
import { IS_DEBUG } from "../config";
// 场景显示
export default () => {
  if (isTest) return <Test />;
  /*----------------------------变量命名------------------------------*/
  const { autoRotate } = useConnect(NMold);
  const [showCollider, setShowCollider] = useState(false); // 显示碰撞体
  const [showPov, setShowPov] = useState(false); // 第一视角
  // 键盘事件
  const map = [
    { name: "forward", keys: ["ArrowUp", "w", "W"] },
    { name: "backward", keys: ["ArrowDown", "s", "S"] },
    { name: "left", keys: ["ArrowLeft", "a", "A"] },
    { name: "right", keys: ["ArrowRight", "d", "D"] },
    { name: "jump", keys: ["Space"] },
  ];
  // 相机抖动
  const shakeConfig = {
    maxYaw: 0.1, // 相机可以在任意方向上偏转的最大数量
    maxPitch: 0.01, // 相机可以向任意方向倾斜的最大数量
    maxRoll: 0.01, // 相机可以在任意方向上滚动的最大数量

    yawFrequency: 0.1, // 偏航旋转的频率
    pitchFrequency: 0.5, // 俯仰旋转的频率
    rollFrequency: 0.4, // 滚动旋转的频率

    intensity: 1, // 抖动的初始强度
    decay: false, // 强度是否随时间衰减
    decayRate: 0.65, // 如果decay=true，这是强度的衰减率
  };
  // 控制器
  const controlConfig = useMemo(
    () => ({
      reverseOrbit: true,
      enableZoom: true,
      enableRotate: true,
      autoRotate: autoRotate,
      autoRotateSpeed: 0.5,
      enableDamping: true,
      dampingFactor: 0.2,
      rotateSpeed: 0.5,
    }),
    [autoRotate]
  );
  /*----------------------------生命周期------------------------------*/
  useEffect(() => {
    const url = window.location.href;
    url.split("?")[1]?.indexOf("debug") > -1 && setShowCollider(true);
    url.split("?")[1]?.indexOf("pov") > -1 && setShowPov(true);
  }, []);

  // function cancelRotate() {
  //   reducer(NMold, RSetState, { autoRotate: false });
  // }
  /*----------------------------场景渲染------------------------------*/

  return (
    <div className="canvas">
      <Canvas
        camera={{ fov: 60, position: [3, 1, 3] }}
        shadows
        // onPointerDown={cancelRotate}
      >
        <KeyboardControls map={map}>
          <Sky sunPosition={[100, 20, 100]} distance={1000} />
          <ambientLight intensity={1} />
          <directionalLight
            position={[100, 100, 100]}
            intensity={1.5}
            castShadow
            shadow-mapSize-width={1024}
            shadow-mapSize-height={1024}
          />
          <Suspense>
            <Physics debug={showCollider}>
              {showPov ? <Pov /> : <Player />}
              <OtherPlayers />
              <Building />
            </Physics>
            {/* <Clouds num={12} /> */}
            <Ocean />
            <Audios />
            {/* 预加载可见对象 */}
            <Preload />
            {/* 允许暂时降低视觉质量以换取更多性能，例如当相机移动时 */}
            <AdaptiveDpr pixelated />
          </Suspense>
          {showPov ? (
            <PointerLockControls />
          ) : (
            <OrbitControls {...controlConfig} makeDefault />
          )}
          {!showPov && <CameraShake {...shakeConfig} />}
          <Perf position="top-right" />
          {IS_DEBUG && <axesHelper args={[500]} />}
        </KeyboardControls>
      </Canvas>
    </div>
  );
};
